package com.augurit.smartform.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.orm.Page;

import com.augurit.common.dao.SysMetaTableDao;
import com.augurit.common.entity.SysMetaTable;
import com.augurit.common.syscode.web.form.SysCodeForm;
import com.augurit.common.util.lang.StringUtils;
import com.augurit.smartform.constant.PageConstant;
import com.augurit.smartform.constant.SqlTypeConstant;
import com.augurit.smartform.dao.SmFunctionDao;
import com.augurit.smartform.dao.SmPageDao;
import com.augurit.smartform.dao.SmartFormDao;
import com.augurit.smartform.database.Column;
import com.augurit.smartform.database.DatabaseParser;
import com.augurit.smartform.database.SQLWrapper;
import com.augurit.smartform.database.Table;
import com.augurit.smartform.display.PageElement;
import com.augurit.smartform.display.PageResolve;
import com.augurit.smartform.display.TagElement;
import com.augurit.smartform.entity.SmFunction;
import com.augurit.smartform.entity.SmPage;
import com.augurit.smartform.service.ISmartFormService;
import com.augurit.smartform.service.IFormExecuteService;

@Service
@Transactional
public class FormExecuteService implements IFormExecuteService {
	@Autowired
	private SmartFormDao smartFormDao;
	@Autowired
	private SmPageDao smPageDao;
	@Autowired
	private SmFunctionDao smFunctionDao;
	@Autowired
	private DatabaseParser databaseParser;
	@Autowired
	private PageResolve pageResolve;
	@Autowired
	private ISmartFormService smartFormService;
	
	/**
	 * 查找并执行后端标签JAVASCRIPT脚本
	 * @param engine
	 * @param request
	 * cuigeqiang
	 */
	public Object executeTagServer(ScriptEngine engine,HttpServletRequest request){
		Map map=request.getParameterMap();
//		String[] pageId=(String[])map.get(PageConstant.KEY_PAGE_ID);
		String[] pageCode=(String[])map.get(PageConstant.KEY_PAGE_CODE);
		String[] componentId=(String[])map.get(PageConstant.KEY_COMPONENT_ID);
		String[] eventMethod=(String[])map.get(PageConstant.KEY_EVENT);
		
//		Long id=Long.parseLong(pageId[0]);
//		SmPage page=smPageDao.get(id);
		SmPage page=smartFormService.getSmPageByPageCode(pageCode[0]);
		Long id=page.getId();
		
		SmFunction function=null;
		SmFunction queryFunction=new SmFunction();
		queryFunction.setFieldId(componentId[0]);
		queryFunction.setPageId(id);
		queryFunction.setEvent(eventMethod[0]);
		List<SmFunction> functions=smFunctionDao.getFunctions(queryFunction);
		if(functions!=null&&functions.size()>0){
			function=functions.get(0);
		}
		return this.evalFunction(engine, page, function);
	}
	
	/**
	 * 查找并执行后端页面JAVASCRIPT脚本
	 * @param engine
	 * @param request
	 * cuigeqiang
	 */
	public void executePageServer(ScriptEngine engine,HttpServletRequest request){
		Map map=request.getParameterMap();
//		String[] pageId=(String[])map.get(PageConstant.KEY_PAGE_ID);
		String[] pageCode=(String[])map.get(PageConstant.KEY_PAGE_CODE);
		
//		Long id=Long.parseLong(pageId[0]);
//		SmPage page=smPageDao.get(id);
		SmPage page=smartFormService.getSmPageByPageCode(pageCode[0]);
		
		this.evalPageJavascript(engine, page);
	}
	
	/**
	 * 查找并执行后端工作流保存之前JAVASCRIPT脚本
	 * @param engine
	 * @param request
	 * cuigeqiang
	 */
	public void executeWfSaveServer(ScriptEngine engine,HttpServletRequest request){
		Map map=request.getParameterMap();
		String[] pageCode=(String[])map.get(PageConstant.KEY_PAGE_CODE);
		
		SmPage page=smartFormService.getSmPageByPageCode(pageCode[0]);
		
		this.evalWfSaveJavascript(engine, page);
	}
	
	/**
	 * 保存表单数据
	 * @param request
	 * cuigeqiang
	 */
	public List<Long>  saveForm(HttpServletRequest request){
		Map requestMap=request.getParameterMap();
		List<Long> ids=new ArrayList<Long>();
		String sourceXmlStr=this.getSourceXmlByRequest(requestMap);
		
		List<Table> deepTables=databaseParser.parseToAscTables(sourceXmlStr);
		this.injectValueToInsertColumn(requestMap, deepTables);
		
		for(Table table : deepTables){
			if(table.isInserting()){
				List<String> insertSqls=SQLWrapper.insertTable(table);
				smartFormDao.executeInsertSql(insertSqls,table);
				ids.add(table.getIdValue());
			}
		}
		return ids;
	}
	
	/**
	 * 保存从表数据
	 * @param request
	 * cuigeqiang
	 */
	public List<Long> saveSlaveForm(HttpServletRequest request){
		Map requestMap=request.getParameterMap();
		List<Long> ids=new ArrayList<Long>();
		String sourceXmlStr=this.getSourceXmlByRequest(requestMap);
		
		if(this.existParentIdValue(requestMap)){
			List<Table> deepTables=new ArrayList<Table>();
			Table currentTable=smartFormService.getCurrentTable(sourceXmlStr);
			deepTables.add(currentTable);
			this.injectValueToInsertColumn(requestMap, deepTables);
			
			for(Table table : deepTables){
				if(table.isInserting()){
					List<String> insertSqls=SQLWrapper.insertTable(table);
					smartFormDao.executeInsertSql(insertSqls,table);
					ids.add(table.getIdValue());
				}
			}
			
		}
		return ids;
	}
	
	/**
	 * 查询表单数据
	 * @param page
	 * @param request
	 * cuigeqiang
	 */
	public void search(Page<Map> page,HttpServletRequest request){
		Map requestMap=request.getParameterMap();
		String sourceXmlStr=this.getSourceXmlByRequest(requestMap);
		
		List<Table> deepTables=databaseParser.parseToAscTables(sourceXmlStr);
		this.injectValueToSelectColumn(requestMap, deepTables);
		for(Table table : deepTables){
			if(table.isSelecting()){
				String selectSql=SQLWrapper.selectTable(table);
				if(page.getPageSize()==10000){
					smartFormDao.setAllPageData(selectSql, page);
				}else{
					smartFormDao.setPageData(selectSql, page);
				}
			}
		}
	}
	
	/**
	 * 得到默认值放入MAP中
	 * @param request
	 * @return
	 * cuigeqiang
	 */
	public Map<String,Object> getDefaultMap(HttpServletRequest request){
		Map<String,Object> defaultMap=new HashMap<String,Object>();
		
		Map requestMap=request.getParameterMap();
		String sourceXmlStr=this.getSourceXmlByRequest(requestMap);
		
		if(StringUtils.isNotBlank(sourceXmlStr)){
			List<Table> deepTables=databaseParser.parseToAscTables(sourceXmlStr);
			for(Table table : deepTables){
				List<Column> columns=table.getColumn();
				for(Column col : columns){
					if(col!=null&&StringUtils.isNotBlank(col.getDefaultValue())){
						String key=col.getObjectName()+PageConstant.STR_SEPERATOR+col.getName();
						String defaultValue=col.getDefaultValue();
						defaultMap.put(key, defaultValue);
					}
				}
			}
		}
		
		return defaultMap;
	}
	
	/**
	 * 从后台加载修改表单的数据
	 * @param pageMap
	 * @param request
	 * cuigeqiang
	 */
	public void loadUpdateData(Map pageMap,HttpServletRequest request){
		Map requestMap=request.getParameterMap();
		
		if(existIdValue(requestMap)){
			String sourceXmlStr=this.getSourceXmlByRequest(requestMap);
			
			String[] idArray=(String[])requestMap.get(PageConstant.KEY_ID);
			String id=idArray[0];
			
			List<Table> deepTables=databaseParser.parseToAscTables(sourceXmlStr);
			
			this.loadUpdateData(pageMap, id, deepTables);
		}
	}
	
	/**
	 * 加载从表数据
	 * @param pageMap
	 * @param request
	 * cuigeqiang
	 */
	public void loadSlaveData(Map pageMap,HttpServletRequest request){
		Map requestMap=request.getParameterMap();
		
		if(this.existParentIdValue(requestMap)){
			String sourceXmlStr=this.getSourceXmlByRequest(requestMap);
			
			String[] parentIdArray=(String[])requestMap.get(PageConstant.KEY_PARENT_ID);
			if(parentIdArray==null||parentIdArray.length==0){
				parentIdArray=(String[])requestMap.get(PageConstant.KEY_MASTER_ENTITY_KEY);
			}
			String parentId=parentIdArray[0];
			pageMap.put(PageConstant.KEY_PARENT_ID, parentId);
			
			Long id=this.getIdByParentId(request);
			
			if(id!=null){
				List<Table> deepTables=new ArrayList<Table>();
				Table currentTable=smartFormService.getCurrentTable(sourceXmlStr);
				deepTables.add(currentTable);
				
				this.loadUpdateData(pageMap, id.toString(), deepTables);
			}
		}
	}
	
	/**
	 * 根据父表单查询子表单ID
	 * @param request
	 * @return
	 * cuigeqiang
	 */
	public Long getIdByParentId(HttpServletRequest request){
		Map requestMap=request.getParameterMap();
		Long id=null;
		
		if(this.existParentIdValue(requestMap)){
			String sourceXmlStr=this.getSourceXmlByRequest(requestMap);
			
			String[] parentIdArray=(String[])requestMap.get(PageConstant.KEY_PARENT_ID);
			if(parentIdArray==null||parentIdArray.length==0){
				parentIdArray=(String[])requestMap.get(PageConstant.KEY_MASTER_ENTITY_KEY);
			}
			String parentId=parentIdArray[0];
			
			List<Table> deepTables=new ArrayList<Table>();
			Table currentTable=smartFormService.getCurrentTable(sourceXmlStr);
			deepTables.add(currentTable);
			this.injectParentIdToSelectColumn(parentId, deepTables);
			
			for(Table table : deepTables){
				if(table.isSelecting()){
					String selectIdSql=SQLWrapper.selectTableId(table);
					id=smartFormDao.getTableId(selectIdSql);
				}
			}
		}
		return id;
	}
	
	/**
	 * 通过ID和PAGECODE从后台加载表单的数据
	 * @param pageMap
	 * @param request
	 * cuigeqiang
	 */
	public void loadDataByPageCodeAndId(Map<String,Object> pageMap,String id,String pageCode){
		if(StringUtils.isNotBlank(id)&&StringUtils.isNotBlank(pageCode)){
			String sourceXmlStr=this.getSourceXmlByPageCode(pageCode);
			List<Table> deepTables=databaseParser.parseToAscTables(sourceXmlStr);
			this.injectIdToSelectColumn(id, deepTables);
			
			for(Table table : deepTables){
				if(table.isSelecting()){
					String selectSql=SQLWrapper.selectTable(table);
					smartFormDao.setPageMapData(selectSql, pageMap);
				}
			}
		}
	}
	
	/**
	 * 通过ID和PAGECODE从后台加载表单的汇总字段数据（工作流相关）
	 * @param pageMap
	 * @param id
	 * @param pageCode
	 * cuigeqiang
	 */
	public void loadSummaryDataByPageCodeAndId(Map<String,Object> summaryMap,String id,String pageCode){
		if(StringUtils.isNotBlank(id)&&StringUtils.isNotBlank(pageCode)){
			String sourceXmlStr=this.getSourceXmlByPageCode(pageCode);
			List<Table> deepTables=databaseParser.parseToAscTables(sourceXmlStr);
			this.injectIdToSelectColumn(id, deepTables);
			
			for(Table table : deepTables){
				if(table.isSelecting()){
					String selectSql=SQLWrapper.selectTable(table);
					smartFormDao.setSummaryMapData(selectSql, table, summaryMap);
				}
			}
		}
	}
	
	/**
	 * 更新表单数据
	 * @param request
	 * cuigeqiang
	 */
	public List<Long> updateForm(HttpServletRequest request){
		Map requestMap=request.getParameterMap();
		List<Long> ids=new ArrayList<Long>();
		
		if(existIdValue(requestMap)){
			String sourceXmlStr=this.getSourceXmlByRequest(requestMap);
			
			List<Table> deepTables=databaseParser.parseToAscTables(sourceXmlStr);
			
			String[] value=(String[])requestMap.get(PageConstant.KEY_ID);
			String id=value[0];
			
			ids=this.updateForm(id,requestMap, deepTables);
		}else{
			List<Long> addIds=saveForm(request);
			ids.addAll(addIds);
		}
		return ids;
	}
	
	/**
	 * 更新表单数据
	 * @param request
	 * cuigeqiang
	 */
	public List<Long> updateSlaveForm(HttpServletRequest request){
		Map requestMap=request.getParameterMap();
		List<Long> ids=new ArrayList<Long>();
		
		if(this.existParentIdValue(requestMap)){
			Long id=this.getIdByParentId(request);
			if(id!=null){
				String sourceXmlStr=this.getSourceXmlByRequest(requestMap);
				List<Table> deepTables=new ArrayList<Table>();
				Table currentTable=smartFormService.getCurrentTable(sourceXmlStr);
				deepTables.add(currentTable);
				
				ids=this.updateForm(id.toString(),requestMap, deepTables);
			}else{
				ids=this.saveSlaveForm(request);
			}
		}
		return ids;
	}
	
	/**
	 * 得到包含OPTION的MAP
	 * @param request
	 * @return
	 * cuigeqiang
	 */
	public Map<String,Object> getOptionMap(HttpServletRequest request){
		Map<String,Object> optionMap=new HashMap<String,Object>();
		
		Map requestMap=request.getParameterMap();
		String sourceXmlStr=this.getSourceXmlByRequest(requestMap);
		if(StringUtils.isNotBlank(sourceXmlStr)){
			PageElement page=pageResolve.paser(sourceXmlStr);
			Map<String,TagElement> elements=page.getElements();
			Iterator it=elements.entrySet().iterator();
			while(it.hasNext()){
				Map.Entry entry=(Map.Entry)it.next();
				TagElement element=(TagElement)entry.getValue();
				List<SysCodeForm> options=element.getOptions();
				String key=element.getPageName().toUpperCase()+PageConstant.STR_SEPERATOR+element.getName().toUpperCase()+PageConstant.OPTIONS_SUFFIX;
				if(options!=null&&options.size()>0){
					optionMap.put(key, options);
				}else{
					optionMap.put(key, new ArrayList<SysCodeForm>());
				}
			}
		}
		return optionMap;
	}
	
	/**
	 * 删除表单数据
	 * @param request
	 * cuigeqiang
	 */
	public void deleteForm(HttpServletRequest request){
		Map requestMap=request.getParameterMap();
		
		if(existIdValue(requestMap)){
			String sourceXmlStr=this.getSourceXmlByRequest(requestMap);
			List<Table> deepTables=new ArrayList<Table>();
			Table currentTable=smartFormService.getCurrentTable(sourceXmlStr);
			deepTables.add(currentTable);
			
			this.injectValueToDeleteColumn(requestMap, deepTables);
			
			for(Table table : deepTables){
				if(table.isDeleting()){
					List<String> deleteSqls=SQLWrapper.deleteTable(table);
					smartFormDao.executeUpdateList(deleteSqls);
				}
			}
		}
	}
	
	/**
	 * 删除表单数据
	 * @param request
	 * cuigeqiang
	 */
	public void deleteFormByCheckedIds(HttpServletRequest request){
		Map requestMap=request.getParameterMap();
		
		String[] ids=this.filterCheckedIds(requestMap);
		if(ids!=null&&ids.length>0){
			String sourceXmlStr=this.getSourceXmlByRequest(requestMap);
			List<Table> deepTables=new ArrayList<Table>();
			Table currentTable=smartFormService.getCurrentTable(sourceXmlStr);
			deepTables.add(currentTable);
			
			for(Table table : deepTables){
				List<String> deleteSqls=SQLWrapper.deleteTable(table,ids);
				smartFormDao.executeUpdateList(deleteSqls);
			}
		}
	}
	
	/**
	 * 跳转到指定页面
	 * @param response
	 * @param pageCode
	 * cuigeqiang
	 */
	public void openPageByCode(HttpServletResponse response,String pageCode){
		String url=PageConstant.PREFIX_OPEN_PAGE_PATH;
		url+=pageCode;
		try {
			response.sendRedirect(url);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 从REQUESTMAP中查找对应的XML字符串
	 * @param request
	 * @return
	 * cuigeqiang
	 */
	private String getSourceXmlByRequest(Map requestMap){
//		String[] pageId=(String[])requestMap.get(PageConstant.KEY_PAGE_ID);
//		Long id=Long.parseLong(pageId[0]);
//		SmPage pageElement=smPageDao.get(id);
		String sourceXmlStr="";
		String[] pageCode=(String[])requestMap.get(PageConstant.KEY_PAGE_CODE);
		sourceXmlStr=this.getSourceXmlByPageCode(pageCode[0]);
		return sourceXmlStr;
	}
	
	/**
	 * 根据PAGECODE获取XML字符串
	 * @param pageCode
	 * @return
	 * cuigeqiang
	 */
	private String getSourceXmlByPageCode(String pageCode){
		String sourceXmlStr="";
		SmPage pageElement=smartFormService.getSmPageByPageCode(pageCode);
		if(pageElement!=null){
			if(StringUtils.isNotBlank(pageElement.getName())){
				String formName=pageElement.getName().toUpperCase();
				SysMetaTable smForm=smartFormService.getLastedSmFormByName(formName);
				if(smForm!=null){
					sourceXmlStr=smForm.getRawXml();
				}
			}
		}
		return sourceXmlStr;
	}
	
	/**
	 * 将值注入到COLUMN中
	 * @param requestMap
	 * @param deepTables
	 * cuigeqiang
	 */
	private void injectValueToInsertColumn(Map requestMap,List<Table> deepTables){
		for(Table table : deepTables){
			List<Column> columns=table.getColumn();
			for(Column column : columns){
				if(column.isForeignKey()){
					String[] value=(String[])requestMap.get(PageConstant.KEY_PARENT_ID);
					if(value!=null&&value.length==1){
						column.setValue(value[0]);
						databaseParser.setSQLValue(column);
					}
				}
				Iterator it=requestMap.entrySet().iterator();
				while(it.hasNext()){
					Map.Entry entry=(Map.Entry)it.next();
					String key=(String)entry.getKey();
					String[] value=(String[])entry.getValue();
					String objectName=column.getObjectName();
					String columnName=column.getName();
					String objColName=objectName+PageConstant.STR_SEPERATOR+columnName;
					if(key.equalsIgnoreCase(objColName)){
						if(value!=null&&value.length>0){
							table.setInserting(true);
							if(value.length==1){
								String valueStr=value[0];
								column.setValue(valueStr.replaceAll("'", "''"));						//将单引号变成数据库可识别的形式
							}else{
								String valueStr="";
								for(int i=0;i<value.length;i++){
									valueStr+=value[i];
									if(i!=value.length-1){
										valueStr+=PageConstant.VALUE_SEPERATOR;
									}
								}
								column.setValue(valueStr.replaceAll("'", "''"));
							}
							databaseParser.setSQLValue(column);
						}
					}
				}
			}
		}
	}
	
	/**
	 * 将值注入到COLUMN中
	 * @param requestMap
	 * @param deepTables
	 * cuigeqiang
	 */
	private void injectValueToUpdateColumn(String id,Map requestMap,List<Table> deepTables){
		for(Table table : deepTables){
			List<Column> columns=table.getColumn();
			for(Column column : columns){
				if("ID".equalsIgnoreCase(column.getName())){
					column.setValue(id);
					table.setIdValue(Long.parseLong(id));
					databaseParser.setSQLValue(column);
				}
				if(column.isForeignKey()){
					String[] value=(String[])requestMap.get(PageConstant.KEY_PARENT_ID);
					if(value!=null&&value.length==1){
						column.setValue(value[0]);
						databaseParser.setSQLValue(column);
					}
				}
				Iterator it=requestMap.entrySet().iterator();
				while(it.hasNext()){
					Map.Entry entry=(Map.Entry)it.next();
					String key=(String)entry.getKey();
					String[] value=(String[])entry.getValue();
					String objectName=column.getObjectName();
					String columnName=column.getName();
					String objColName=objectName+PageConstant.STR_SEPERATOR+columnName;
					if(key.equalsIgnoreCase(objColName)){
						if(value!=null&&value.length>0){
							table.setUpdating(true);
							if(value.length==1){
								String valueStr=value[0];
								column.setValue(valueStr.replaceAll("'", "''"));						//将单引号变成数据库可识别的形式
								this.modifyDateColumn(column);
							}else{
								String valueStr="";
								for(int i=0;i<value.length;i++){
									valueStr+=value[i];
									if(i!=value.length-1){
										valueStr+=PageConstant.VALUE_SEPERATOR;
									}
								}
								column.setValue(valueStr.replaceAll("'", "''"));
							}
							databaseParser.setSQLValue(column);
						}
					}
				}
			}
		}
	}
	
	/**
	 * 将值注入到COLUMN中
	 * @param requestMap
	 * @param deepTables
	 * cuigeqiang
	 */
	private void injectValueToDeleteColumn(Map requestMap,List<Table> deepTables){
		for(Table table : deepTables){
			List<Column> columns=table.getColumn();
			for(Column column : columns){
				if("ID".equalsIgnoreCase(column.getName())){
					String[] value=(String[])requestMap.get(PageConstant.KEY_ID);
					if(value.length==1){
						table.setDeleting(true);
						column.setValue(value[0]);
						databaseParser.setSQLValue(column);
					}
				}
			}
		}
	}
	
	/**
	 * 将值注入到COLUMN中
	 * @param requestMap
	 * @param deepTables
	 * cuigeqiang
	 */
	private void injectIdToSelectColumn(String id,List<Table> deepTables){
		for(Table table : deepTables){
			table.setSelecting(true);
			List<Column> columns=table.getColumn();
			for(Column column : columns){
				if("ID".equalsIgnoreCase(column.getName())){
					if(StringUtils.isNotBlank(id)){
						column.setValue(id);
						databaseParser.setQuerySQLValue(column);
					}
				}
			}
		}
	}
	
	/**
	 * 将父表单主键值注入到COLUMN中
	 * @param requestMap
	 * @param deepTables
	 * cuigeqiang
	 */
	private void injectParentIdToSelectColumn(String parentId,List<Table> deepTables){
		for(Table table : deepTables){
			table.setSelecting(true);
			List<Column> columns=table.getColumn();
			for(Column column : columns){
				if(column.isForeignKey()){
					if(StringUtils.isNotBlank(parentId)){
						column.setValue(parentId);
						databaseParser.setQuerySQLValue(column);
					}
				}
			}
		}
	}
	
	/**
	 * 将值注入到COLUMN中
	 * @param requestMap
	 * @param deepTables
	 * cuigeqiang
	 */
	private void injectValueToSelectColumn(Map requestMap,List<Table> deepTables){
		for(Table table : deepTables){
			table.setSelecting(true);
			List<Column> columns=table.getColumn();
			for(Column column : columns){
				Iterator it=requestMap.entrySet().iterator();
				while(it.hasNext()){
					Map.Entry entry=(Map.Entry)it.next();
					String key=(String)entry.getKey();
					String[] value=(String[])entry.getValue();
					String objectName=column.getObjectName();
					String columnName=column.getName();
					String objColName=objectName+PageConstant.STR_SEPERATOR+columnName;
					if(key.equalsIgnoreCase(objColName)){
//						table.setSelecting(true);
						if(value!=null&&value.length>0){
							if(value.length==1){
								column.setValue(value[0]);
							}else{
								String valueStr="";
								for(int i=0;i<value.length;i++){
									valueStr+=value[i];
									if(i!=value.length-1){
										valueStr+=PageConstant.VALUE_SEPERATOR;
									}
								}
								column.setValue(valueStr);
							}
							databaseParser.setSQLValue(column);
							databaseParser.setQuerySQLValue(column);
						}
					}
				}
			}
		}
	}
	
	
	/**
	 * 执行SCRIPTENGINE
	 * @param engine
	 * @param page
	 * @param function
	 * cuigeqiang
	 */
	private Object evalFunction(ScriptEngine engine,SmPage page,SmFunction function){
		Object result=null;
		if(engine!=null&&page!=null&&function!=null){
			String serverJavascript=page.getServerJavascript();
			Object[] args=this.getArgArray(function);
			try {
				engine.eval(serverJavascript);
			} catch (ScriptException e) {
				e.printStackTrace();
			}
			if (engine instanceof Invocable) {
	            Invocable invEngine = (Invocable) engine;
	            
				try {
					result = invEngine.invokeFunction(function.getFunction(),args);
				} catch (ScriptException e) {
					e.printStackTrace();
				} catch (NoSuchMethodException e) {
					e.printStackTrace();
				}
	            System.out.println("[Java] result: " + result);
	        } else{
	            System.out.println("NOT Invocable");
	        }
		}
		return result;
	}
	
	/**
	 * 执行页面SCRIPTENGINE
	 * @param engine
	 * @param page
	 * @param function
	 * cuigeqiang
	 */
	private void evalPageJavascript(ScriptEngine engine,SmPage page){
		if(StringUtils.isNotBlank(page.getServerJavascript())){
			String serverJavascript=page.getServerJavascript();
			try {
				engine.eval(serverJavascript);
			} catch (ScriptException e) {
				e.printStackTrace();
			}
			if (engine instanceof Invocable) {
	            Invocable invEngine = (Invocable) engine;
				try {
					invEngine.invokeFunction(PageConstant.PAGE_FUNCTION_NAME);
				} catch (ScriptException e) {
					e.printStackTrace();
				} catch (NoSuchMethodException e) {
					e.printStackTrace();
				}
	        } else{
	            System.out.println("NOT Invocable");
	        }
		}
	}	
	
	/**
	 * 执行页面SCRIPTENGINE
	 * @param engine
	 * @param page
	 * @param function
	 * cuigeqiang
	 */
	private void evalWfSaveJavascript(ScriptEngine engine,SmPage page){
		String serverJavascript="";
		if(StringUtils.isNotBlank(page.getServerJavascript())){
			serverJavascript=page.getServerJavascript();
			try {
				engine.eval(serverJavascript);
			} catch (ScriptException e) {
				e.printStackTrace();
			}
		}
		if (engine instanceof Invocable) {
            Invocable invEngine = (Invocable) engine;
			try {
				if(this.existFunction(serverJavascript, PageConstant.BEFORE_WF_SAVE)){
					invEngine.invokeFunction(PageConstant.BEFORE_WF_SAVE);
				}
			} catch (ScriptException e) {
				e.printStackTrace();
			} catch (NoSuchMethodException e) {
				e.printStackTrace();
			}
        } else{
            System.out.println("NOT Invocable");
        }
	}
	
	/**
	 * 将字符串参数实体对象
	 * @param function
	 * @return
	 * cuigeqiang
	 */
	private Object[] getArgArray(SmFunction function){
		List argList=new ArrayList();
		if(function!=null){
			String argStr=function.getArgument();
			if(StringUtils.isNotBlank(argStr)){
				String[] argStrArray=argStr.split(",");
				for(String arg : argStrArray){
					if(arg.indexOf("\"")>=0||arg.indexOf("'")>=0){
						String argTrim=arg.trim();
						String strObj=argTrim.substring(1, argTrim.length()-1);
						argList.add(strObj);
					}else{
						Double doubleObj=Double.parseDouble(arg);
						argList.add(doubleObj);
					}
				}
			}
		}
		return argList.toArray();
	}
	
	/**
	 * 调整时间的值成格式YYYY-mm-DD hh:MM:ss
	 * @param column
	 * cuigeqiang
	 */
	private void modifyDateColumn(Column column){
		if(SqlTypeConstant.DATE.equalsIgnoreCase(column.getSqlType())&&column.getValue().length()>19){
			column.setValue(column.getValue().substring(0, 19));
		}
	}
	
	/**
	 * 判断是否满足更新的条件
	 * @param requestMap
	 * @return
	 * cuigeqiang
	 */
	private boolean existIdValue(Map requestMap){
		boolean bol=false;
		String[] idArray=(String[])requestMap.get(PageConstant.KEY_ID);
		if(idArray!=null&&idArray.length==1){
			String id=idArray[0];
			bol=StringUtils.isNotBlank(id);
		}
		return bol;
	}
	
	/**
	 * 过滤选中的ID值
	 * @param requestMap
	 * @return
	 * cuigeqiang
	 */
	private String[] filterCheckedIds(Map requestMap){
		String[] returnArr={};
		List<String> list=new ArrayList<String>();
		String[] checkedIds=(String[])requestMap.get(PageConstant.KEY_CHECKEDIDS);
		if(checkedIds!=null&&checkedIds.length>0){
			for(String id : checkedIds){
				if(StringUtils.isNotBlank(id)){
					list.add(id);
				}
			}
		}
		return list.toArray(returnArr);
	}
	
	/**
	 * 判断是否满足更新从表的条件
	 * @param requestMap
	 * @return
	 * cuigeqiang
	 */
	private boolean existParentIdValue(Map requestMap){
		boolean bol=false;
		String[] parentIdArray=(String[])requestMap.get(PageConstant.KEY_PARENT_ID);
		if(parentIdArray==null||parentIdArray.length==0){
			parentIdArray=(String[])requestMap.get(PageConstant.KEY_MASTER_ENTITY_KEY);
		}
		if(parentIdArray!=null&&parentIdArray.length==1){
			String pId=parentIdArray[0];
			bol=StringUtils.isNotBlank(pId);
		}
		
		return bol;
	}
	
	/**
	 * 判断函数是否在后端JS中
	 * @param serverJs
	 * @param functionName
	 * @return
	 * cuigeqiang
	 */
	private boolean existFunction(String serverJs,String functionName){
		boolean bol=false;
		if(StringUtils.isNotBlank(serverJs)&&StringUtils.isNotBlank(functionName)){
			Pattern pattern = Pattern.compile("function\\s+"+functionName+"\\s*\\(");
			Matcher matcher=pattern.matcher(serverJs);
			if(matcher.find()){
				bol=true;
			}
		}
		return bol;
	}
	
	/**
	 * 从后台加载修改表单的数据
	 * @param pageMap
	 * @param request
	 * cuigeqiang
	 */
	private void loadUpdateData(Map pageMap,String id,List<Table> deepTables){
		this.injectIdToSelectColumn(id, deepTables);
		
		for(Table table : deepTables){
			if(table.isSelecting()){
				String selectSql=SQLWrapper.selectTable(table);
				smartFormDao.setPageMapData(selectSql, pageMap,table);
			}
		}
	}
	
	/**
	 * 更新表单数据
	 * @param request
	 * cuigeqiang
	 */
	private List<Long> updateForm(String id,Map requestMap,List<Table> deepTables){
		List<Long> ids=new ArrayList<Long>();
		this.injectValueToUpdateColumn(id,requestMap, deepTables);
		
		for(Table table : deepTables){
			ids.add(table.getIdValue());
			if(table.isUpdating()){
				List<String> updateSqls=SQLWrapper.updateTable(table);
				smartFormDao.executeUpdateList(updateSqls);
			}
		}
		return ids;
	}
}
